package com.one.square.core.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.JWSObject;
import com.one.square.core.constant.SecurityConstants;
import com.one.square.core.exception.BizException;
import lombok.SneakyThrows;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.List;

/**
 * @author cwm
 * @Description JWT工具类
 * @date 2021/10/25 下午4:28
 * @Version 1.0
 */
public class JwtUtils {
    @SneakyThrows
    public static JSONObject getJwtPayload() {
        String token = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader(SecurityConstants.AUTHORIZATION_KEY);
        if (StrUtil.isBlank(token)|| !StrUtil.startWithIgnoreCase(token, SecurityConstants.JWT_PREFIX)) {
            throw  new BizException("请携带正确的token");
        }
        token = StrUtil.replaceIgnoreCase(token, SecurityConstants.JWT_PREFIX, Strings.EMPTY);
        String payload = StrUtil.toString(JWSObject.parse(token).getPayload());
        JSONObject jsonObject = JSONUtil.parseObj(payload);
        return jsonObject;
    }

    public static JSONObject getJwtPayload(String tokenValue) throws ParseException {
        String payload = StrUtil.toString(JWSObject.parse(tokenValue).getPayload());
        JSONObject jsonObject = JSONUtil.parseObj(payload);
        return jsonObject;
    }

    /**
     * 解析JWT获取用户ID
     *
     * @return
     */
    public static Long getUserId() {
        Long id = getJwtPayload().getLong(SecurityConstants.USER_ID_KEY);
        return id;
    }

    /**
     * 解析JWT获取获取用户名
     *
     * @return
     */
    public static String getUsername() {
        String username = getJwtPayload().getStr(SecurityConstants.USER_NAME_KEY);
        return username;
    }

    /**
     * 解析JWT获取获取客户端id
     * @return
     */
    public static String getclientId(){
        String clientId = getJwtPayload().getStr(SecurityConstants.CLIENT_ID_KEY);
        return clientId;
    }

    /**
     * 解析JWT获取获取授权类型
     * @return
     */
    public static String getGrantType(){
        String grantType = getJwtPayload().getStr(SecurityConstants.GRANT_TYPE_KEY);
        return grantType;
    }

    /**
     * JWT获取用户角色列表
     *
     * @return 角色列表
     */
    public static List<String> getRoles() {
        List<String> roles = null;
        JSONObject payload = getJwtPayload();
        if (payload.containsKey(SecurityConstants.JWT_AUTHORITIES_KEY)) {
            roles = payload.getJSONArray(SecurityConstants.JWT_AUTHORITIES_KEY).toList(String.class);
        }
        return roles;
    }
}
